package john.wenzi.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

public class AESTest2 {
	private static Map<Integer, String> keyMap = new HashMap<Integer, String>();
	public static void main(String[] args) throws Exception {
		/*System.out.println("加密");
		String id =  getGenerateKey();
		System.out.println(id);
		File f = new File("D:/test.txt");
		File f1 = encrypt(f,"txt",id);
		FileUtils.copyFile(f1, f);
		f1.delete();
		System.out.println("解密");
		File f2 = new File("D:/test.txt");
		File f3 = decryptFile(f2,"txt",id);
		FileUtils.copyFile(f3, f2);
		f3.delete();*/
		genKeyPair();
		System.out.println(keyMap.get(0));
		System.out.println(keyMap.get(1));
	}
	/**
     * 随机生成AES密钥
     */
	public static String getGenerateKey()throws Exception{
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] encoded = secretKey.getEncoded();
        return Base64.encodeBase64String(encoded);
    }
	/**
     * 将String类型的密钥转化为SecretKey类型
     */
    private static SecretKey StringToSecretKey(String generateKey){
        byte[] bytes = Base64.decodeBase64(generateKey);
        SecretKeySpec spec = new SecretKeySpec(bytes,"AES");
        return  spec;
    }

    public static File encrypt(File sourceFile,String fileType, String generateKey)throws Exception{
        SecretKey secretKey = StringToSecretKey(generateKey);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
        
        File encrypfile = null;  
        InputStream inputStream = null;  
        OutputStream outputStream = null;  
        try {  
            inputStream = new FileInputStream(sourceFile);  
            encrypfile = File.createTempFile(sourceFile.getName()+"1", fileType);  
            outputStream = new FileOutputStream(encrypfile);  
            //以加密流写入文件  
            CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);  
            byte[] cache = new byte[1024];  
            int nRead = 0;  
            while ((nRead = cipherInputStream.read(cache)) != -1) {  
                outputStream.write(cache, 0, nRead);  
                outputStream.flush();  
            }  
            cipherInputStream.close();  
        }  catch (FileNotFoundException e) {  
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
        }  catch (IOException e) {  
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
        } finally {  
            try {  
                inputStream.close();  
                outputStream.close(); 
            } catch (IOException e) {  
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
            }  
        }  
        return encrypfile; 
    }
	  
	public static File decryptFile(File sourceFile,String fileType,String generateKey)throws Exception{ 
		SecretKey secretKey = StringToSecretKey(generateKey);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE,secretKey);
        
        File encrypfile = null;  
        InputStream inputStream = null;  
        OutputStream outputStream = null;  
        try {  
            inputStream = new FileInputStream(sourceFile);  
            encrypfile = File.createTempFile(sourceFile.getName()+"1", fileType);  
            outputStream = new FileOutputStream(encrypfile);  
            //以加密流写入文件  
            CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);  
            byte[] cache = new byte[1024];  
            int nRead = 0;  
            while ((nRead = cipherInputStream.read(cache)) != -1) {  
                outputStream.write(cache, 0, nRead);  
                outputStream.flush();  
            }  
            cipherInputStream.close();  
        }  catch (FileNotFoundException e) {  
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
        }  catch (IOException e) {  
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
        } finally {  
            try {  
                inputStream.close();  
            } catch (IOException e) {  
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
            }  
            try {  
                outputStream.close();  
            } catch (IOException e) {  
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
            }  
        }  
        return encrypfile; 
    }
	
	
	
	public static void genKeyPair() throws NoSuchAlgorithmException {  
		// KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象  
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
		// 初始化密钥对生成器，密钥大小为96-1024位  
		keyPairGen.initialize(1024,new SecureRandom());  
		// 生成一个密钥对，保存在keyPair中  
		KeyPair keyPair = keyPairGen.generateKeyPair();  
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥  
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥  
		String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));  
		// 得到私钥字符串  
		String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));  
		// 将公钥和私钥保存到Map
		keyMap.put(0,publicKeyString);  //0表示公钥
		keyMap.put(1,privateKeyString);  //1表示私钥
	}  
	/** 
	 * RSA公钥加密 
	 *  
	 * @param str 
	 *            加密字符串
	 * @param publicKey 
	 *            公钥 
	 * @return 密文 
	 * @throws Exception 
	 *             加密过程中的异常信息 
	 */  
	public static String encrypt( String str, String publicKey ) throws Exception{
		//base64编码的公钥
		byte[] decoded = Base64.decodeBase64(publicKey);
		RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
		//RSA加密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
		return outStr;
	}

	/** 
	 * RSA私钥解密
	 *  
	 * @param str 
	 *            加密字符串
	 * @param privateKey 
	 *            私钥 
	 * @return 铭文
	 * @throws Exception 
	 *             解密过程中的异常信息 
	 */  
	public static String decrypt(String str, String privateKey) throws Exception{
		//64位解码加密后的字符串
		byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
		//base64编码的私钥
		byte[] decoded = Base64.decodeBase64(privateKey);  
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));  
		//RSA解密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, priKey);
		String outStr = new String(cipher.doFinal(inputByte));
		return outStr;
	}

}
